package com.golden.procedure.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.golden.procedure.dao.WorkAttachmentMapper;
import com.golden.procedure.dao.WorkOrderPickMapper;
import com.golden.procedure.dao.WorkOrderPickTimesMapper;
import com.golden.procedure.dao.WorkPhotoFilmMapper;
import com.golden.procedure.dao.WorkPhotoProductMapper;
import com.golden.procedure.domain.WorkAttachmentAccountDO;
import com.golden.procedure.domain.WorkAttachmentDO;
import com.golden.procedure.domain.WorkOrderDO;
import com.golden.procedure.domain.WorkOrderPhotographyDO;
import com.golden.procedure.domain.WorkPhotoProductDO;
import com.golden.procedure.entity.WorkAttachment;
import com.golden.procedure.entity.WorkAttachmentExample;
import com.golden.procedure.entity.WorkPhotoFilm;
import com.golden.procedure.entity.WorkPhotoFilmExample;
import com.golden.procedure.entity.WorkPhotoProductExample;
import com.golden.procedure.query.WorkAttachmentQueryDO;
import com.golden.procedure.result.ResultDO;
import com.golden.procedure.result.ResultSupport;
import com.golden.procedure.service.IWorkAttachmentService;
import com.golden.procedure.service.IWorkOrderPickService;
import com.golden.procedure.service.IWorkOrderService;
import com.golden.procedure.service.IWorkPhotoProductService;
import com.golden.procedure.service.IWorkPhotographyService;
import com.golden.procedure.util.BonConstant;

@Service("workAttachmentService")
public class WorkAttachmentService extends BaseService implements IWorkAttachmentService {

	@Autowired
	WorkOrderPickMapper workOrderPickMapper;
	@Autowired
	WorkOrderPickTimesMapper workOrderPickTimesMapper;
	@Autowired
	WorkAttachmentMapper workAttachmentMapper;
	@Autowired
	WorkPhotoProductMapper workPhotoProductMapper;
	@Autowired
	WorkPhotoFilmMapper workPhotoFilmMapper;
	@Autowired
	IWorkOrderService workOrderService;
	@Autowired
	IWorkAttachmentService workAttatchmentService;
	@Autowired
	IWorkOrderPickService workOrderPickService;
	@Autowired
	IWorkPhotoProductService workPhotoProductService;
	@Autowired
	IWorkPhotographyService workPhotographyService;

	/** 导入文件（单个文件） */
	@Override
	public ResultDO add(Integer workPhotographyID, Integer source, Integer fileID, String url, String businessNo) {

		ResultDO result = new ResultSupport();

		// 1.查询拍摄信息
		ResultDO resultDO = workPhotographyService.get(workPhotographyID);
		if (!resultDO.isSuccess()) {
			return resultDO;
		}
		WorkOrderPhotographyDO photographyDO = (WorkOrderPhotographyDO) resultDO.getModel(ResultDO.FIRST_MODEL_KEY);
		// 2.查询工单信息
		resultDO = workOrderService.get(photographyDO.getWorkOrderID());
		if (!resultDO.isSuccess()) {
			return resultDO;
		}
		WorkOrderDO orderDO = (WorkOrderDO) resultDO.getModel(ResultDO.FIRST_MODEL_KEY);

		// 3.有业务单号时，查询该业务单号使用的片源
		Integer businessSource = -1;
		if (StringUtils.isNotEmpty(businessNo)) {
			businessSource = workOrderPickService.getSource(businessNo);
		}

		// 从地址中截取文件名
		String fileName = url.substring(url.lastIndexOf("/") + 1);

		WorkAttachment entity = new WorkAttachment();
		// 查询是否有重复的文件名
		WorkAttachmentExample example = new WorkAttachmentExample();
		WorkAttachmentExample.Criteria criteria = example.createCriteria();
		criteria.andWorkOrderIDEqualTo(photographyDO.getWorkOrderID());
		criteria.andWorkPhotographyIDEqualTo(workPhotographyID);
		criteria.andFileNameEqualTo(fileName);
		criteria.andSourceEqualTo(source); // 相同片源

		List<WorkAttachment> list = workAttachmentMapper.selectByExample(example);
		// 新增、更新
		boolean isUpdate = false;
		if (null != list && list.size() > 0) {
			entity = list.get(0);
			isUpdate = true;
		} else {
			// 新增
			entity.setWorkPhotographyID(workPhotographyID);
			entity.setWorkOrderID(photographyDO.getWorkOrderID());
			entity.setProcessInstanceID(orderDO.getProcessInstanceID());
			entity.setTaskID(photographyDO.getTaskID());
			entity.setAttachType(BonConstant.ATTACHMENT_TYPE_PHOTO); // 1照片
			entity.setFileName(fileName);
			entity.setSource(source); // 片源
			// entity.setStatus(BonConstant.STATUS_TRUE); // 选中
			entity.setIsDelete(BonConstant.DB_NORMAL);
			entity.setCreatetime(Calendar.getInstance().getTime());
		}
		// entity.setFileDir(domain.getFileDir());

		String thumbnailUrl = "";
		String bigThumbnailUrl = "";
		entity.setThumbnailUrl(thumbnailUrl);
		entity.setBigThumbnailUrl(bigThumbnailUrl);
		entity.setDownloadUrl(url);
		entity.setFileID(fileID);
		entity.setModifitime(Calendar.getInstance().getTime());

		int ret = 0;
		if (isUpdate) {
			// 更新
			ret = workAttachmentMapper.updateByPrimaryKeySelective(entity);
			if (ret < 1) {
				result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg("照片添加失败");
				result.setSuccess(false);
			}
		} else {
			// 准备批量导入照片数据
			workAttachmentMapper.insert(entity);
			// 如果有业务单号，且来源与选片来源一致，或是客户自备底片，则默认入底，写入入底数据
			// 从照片处导入新增照片的入底数据
			if (businessSource >= 0) {
				if (businessSource == source || source == BonConstant.PHOTO_SOURCE_CUSTOMER) {
					// 如果有业务单号，则写入入底数据（所有照片默认入底）
					WorkPhotoFilm film = new WorkPhotoFilm();
					film.setAttachmentID(entity.getId());
					film.setBusinessNo(businessNo);
					film.setWorkOrderID(entity.getWorkOrderID());
					film.setSource(entity.getSource());
					film.setStatus(BonConstant.STATUS_TRUE);
					film.setIsDelete(entity.getIsDelete());
					workPhotoFilmMapper.insert(film);
				}
			}
		}

		return result;
	}

	/**
	 * 添加选片记录 <b>Description: 添加选片记录</b><br>
	 * 
	 * @param domain
	 * @return ResultDO
	 * @Note <b>Author:</b> Reading.Reagan <br>
	 *       <b>Date:</b> 2018年9月20日 下午3:43:42 <br>
	 *       <b>Version:</b> 1.0
	 */
	@Override
	public ResultDO test(WorkAttachmentDO domain) {

		ResultDO result = new ResultSupport();

		// 参数：工单id，拍摄id，来源
		if (isNumberInValid(domain.getWorkPhotographyID()) || isNumberInValid(domain.getWorkOrderID())
				|| null == domain.getSource()) {
			result.setSuccess(false);
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("参数错误");
			return result;
		}

		// 1.查询拍摄信息
		ResultDO resultDO = workPhotographyService.get(domain.getWorkPhotographyID());
		if (!resultDO.isSuccess()) {
			return resultDO;
		}
		WorkOrderPhotographyDO photographyDO = (WorkOrderPhotographyDO) resultDO.getModel(ResultDO.FIRST_MODEL_KEY);
		// 2.查询工单信息
		resultDO = workOrderService.get(domain.getWorkOrderID());
		if (!resultDO.isSuccess()) {
			return resultDO;
		}
		WorkOrderDO orderDO = (WorkOrderDO) resultDO.getModel(ResultDO.FIRST_MODEL_KEY);

		// 3.有业务单号时，查询该业务单号使用的片源
		Integer businessSource = -1;
		if (StringUtils.isNotEmpty(domain.getBusinessNo())) {
			businessSource = workOrderPickService.getSource(domain.getBusinessNo());
		}

		// 待入底文件名
		List<String> rdList = new ArrayList<String>();
		List<WorkAttachment> batchList = new ArrayList<WorkAttachment>();

		// TODO: 测试照片
		int count = 60;
		if (!isNumberInValid(domain.getCount())) {
			count = domain.getCount();
		}

		// TODO: 测试数据
		List<String> picList = new ArrayList<String>();
		picList.add("https://gaoqiang19514.github.io/waterfall/images/10.jpg");
		picList.add("https://gaoqiang19514.github.io/waterfall/images/19.jpg");
		picList.add("https://gaoqiang19514.github.io/waterfall/images/22.jpg");
		picList.add("https://gaoqiang19514.github.io/waterfall/images/12.jpg");
		picList.add("https://gaoqiang19514.github.io/waterfall/images/21.jpg");
		picList.add("https://gaoqiang19514.github.io/waterfall/images/18.jpeg");
		picList.add("https://gaoqiang19514.github.io/waterfall/images/17.jpeg");
		picList.add("https://gaoqiang19514.github.io/waterfall/images/3.jpg");
		picList.add("https://gaoqiang19514.github.io/waterfall/images/25.jpg");
		picList.add("https://gaoqiang19514.github.io/waterfall/images/24.jpg");
		for (int i = 0; i < count; i++) {
			WorkAttachment entity = new WorkAttachment();
			// 查询是否有重复的文件名
			String fileName = "photo20181011" + i;
			WorkAttachmentExample example = new WorkAttachmentExample();
			WorkAttachmentExample.Criteria criteria = example.createCriteria();
			criteria.andWorkOrderIDEqualTo(domain.getWorkOrderID());
			criteria.andWorkPhotographyIDEqualTo(domain.getWorkPhotographyID());
			criteria.andFileNameEqualTo(fileName);
			criteria.andSourceEqualTo(domain.getSource()); // 相同片源

			List<WorkAttachment> list = workAttachmentMapper.selectByExample(example);
			// 新增、更新
			boolean isUpdate = false;
			if (null != list && list.size() > 0) {
				entity = list.get(0);
				isUpdate = true;
			} else {
				// 新增
				entity.setWorkPhotographyID(domain.getWorkPhotographyID());
				entity.setWorkOrderID(domain.getWorkOrderID());
				entity.setProcessInstanceID(orderDO.getProcessInstanceID());
				entity.setTaskID(photographyDO.getTaskID());
				entity.setAttachType(BonConstant.ATTACHMENT_TYPE_PHOTO); // 1照片
				entity.setFileName(fileName);
				entity.setSource(domain.getSource()); // 片源
				entity.setStatus(BonConstant.STATUS_TRUE); // 选中
				entity.setIsDelete(BonConstant.DB_NORMAL);
				entity.setCreatetime(Calendar.getInstance().getTime());
			}

			entity.setFileDir("/image/photo/201810/" + fileName);
			entity.setThumbnailUrl(picList.get(i % 10));
			entity.setBigThumbnailUrl(picList.get(i % 10));
			entity.setDownloadUrl(picList.get(i % 10));
			entity.setModifitime(Calendar.getInstance().getTime());

			int ret = 0;
			if (isUpdate) {
				// 更新
				ret = workAttachmentMapper.updateByPrimaryKeySelective(entity);
				if (ret < 1) {
					result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
					result.setErrorMsg("照片添加失败");
					result.setSuccess(false);
				}
			} else {
				// 准备批量导入照片数据
				batchList.add(entity);
				// 如果有业务单号，且来源与选片来源一致，或是客户自备底片，则默认入底，写入入底数据
				if (businessSource >= 0) {
					if (businessSource == domain.getSource()
							|| domain.getSource() == BonConstant.PHOTO_SOURCE_CUSTOMER) {
						// 如果有业务单号，则写入入底数据（所有照片默认入底）
						rdList.add(entity.getFileName());
					}
				}
			}
		}

		// 批量导入照片数据
		if (batchList.size() > 0) {
			int ret = workAttachmentMapper.insertBatch(batchList);
			if (ret < 1) {
				// 照片数据导入失败
				result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg("数据导入失败");
				result.setSuccess(false);
				return result;
			}
		}

		// 从照片处导入新增照片的入底数据
		if (rdList.size() > 0) {
			WorkAttachmentExample example = new WorkAttachmentExample();
			WorkAttachmentExample.Criteria criteria = example.createCriteria();
			criteria.andWorkOrderIDEqualTo(domain.getWorkOrderID());
			criteria.andWorkPhotographyIDEqualTo(domain.getWorkPhotographyID());
			criteria.andFileNameIn(rdList);
			criteria.andSourceEqualTo(domain.getSource());
			List<WorkAttachment> list = workAttachmentMapper.selectByExample(example);

			// 新文件入底
			List<WorkPhotoFilm> filmList = new ArrayList<WorkPhotoFilm>();
			for (WorkAttachment data : list) {
				WorkPhotoFilm film = new WorkPhotoFilm();
				film.setAttachmentID(data.getId());
				film.setBusinessNo(domain.getBusinessNo());
				film.setWorkOrderID(data.getWorkOrderID());
				film.setSource(data.getSource());
				film.setStatus(BonConstant.STATUS_TRUE);
				film.setIsDelete(data.getIsDelete());
				filmList.add(film);
			}
			if (filmList.size() > 0) {
				int ret = workPhotoFilmMapper.insertBatch(filmList);
				if (ret < 1) {
					// 入底数据导入失败
					result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
					result.setErrorMsg("数据初始化失败");
					result.setSuccess(false);
					return result;
				}
			}
		}

		return result;
	}

	@Override
	public ResultDO query(WorkAttachmentQueryDO queryDO) {
		ResultDO result = new ResultSupport();

		List<WorkAttachmentDO> doList = new ArrayList<WorkAttachmentDO>();
		WorkAttachmentExample example = new WorkAttachmentExample();
		WorkAttachmentExample.Criteria criteria = example.createCriteria();
		// 工单ID
		if (!isNumberInValid(queryDO.getWorkOrderID())) {
			criteria.andWorkOrderIDEqualTo(queryDO.getWorkOrderID());
		}
		// 拍摄记录ID
		if (!isNumberInValid(queryDO.getWorkPhotographyID())) {
			criteria.andWorkPhotographyIDEqualTo(queryDO.getWorkPhotographyID());
		}
		// 文件类型
		if (null != queryDO.getAttachmentType()) {
			criteria.andAttachTypeEqualTo(queryDO.getAttachmentType());
		}
		// 片源
		if (null != queryDO.getSource()) {
			criteria.andSourceEqualTo(queryDO.getSource());
		}
		// 片源
		if (null != queryDO.getSources() && queryDO.getSources().length > 0) {
			criteria.andSourceIn(Arrays.asList(queryDO.getSources()));
		}
		// 状态
		if (null != queryDO.getStatus() && queryDO.getStatus().length > 0) {
			criteria.andStatusIn(Arrays.asList(queryDO.getStatus()));
		}
		criteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL);
		example.setOrderByClause(" createtime desc, id desc ");

		if (queryDO.isPage()) {
			example.setLimitByPage(queryDO.getStart() + "," + queryDO.getPageRows());
			int count = workAttachmentMapper.countByExample(example);
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
		}

		List<WorkAttachment> list = workAttachmentMapper.selectByExample(example);
		if (null != list && list.size() > 0) {
			doList = getWorkAttachmentDOList(list);
		}

		result.setModel(ResultDO.FIRST_MODEL_KEY, doList);
		return result;
	}

	@Override
	public ResultDO edit(WorkAttachmentDO domain) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Integer countShotNum(Integer workPhotographyID) {
		if (isNumberInValid(workPhotographyID)) {
			return -1;
		}
		WorkAttachmentExample example = new WorkAttachmentExample();
		WorkAttachmentExample.Criteria criteria = example.createCriteria();
		criteria.andWorkPhotographyIDEqualTo(workPhotographyID);
		criteria.andAttachTypeEqualTo(BonConstant.ATTACHMENT_TYPE_PHOTO); // 照片
		criteria.andSourceNotEqualTo(BonConstant.PHOTO_SOURCE_CUSTOMER); // 排除客户自备片
		return workAttachmentMapper.countByExample(example);
	}

	public Integer countPickNum(Integer workPhotographyID) {
		if (isNumberInValid(workPhotographyID)) {
			return -1;
		}
		WorkAttachmentExample example = new WorkAttachmentExample();
		WorkAttachmentExample.Criteria criteria = example.createCriteria();
		criteria.andWorkPhotographyIDEqualTo(workPhotographyID);
		criteria.andAttachTypeEqualTo(BonConstant.ATTACHMENT_TYPE_PHOTO); // 照片
		criteria.andSourceNotEqualTo(BonConstant.PHOTO_SOURCE_CUSTOMER); // 排除客户自备片
		criteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL); // 不计入删除的照片
		return workAttachmentMapper.countByExample(example);
	}

	@Override
	public ResultDO get(Integer id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ResultDO delete(WorkAttachmentDO domain) {
		ResultDO result = new ResultSupport();

		WorkAttachmentExample example = new WorkAttachmentExample();
		WorkAttachmentExample.Criteria criteria = example.createCriteria();
		if (!isNumberInValid(domain.getId())) {
			criteria.andIdEqualTo(domain.getId());
		}
		if (null != domain.getIds() && domain.getIds().length > 0) {
			criteria.andIdIn(Arrays.asList(domain.getIds()));
		}
		criteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL);
		WorkAttachment entity = new WorkAttachment();
		entity.setIsDelete(BonConstant.DB_DELETE);
		entity.setModifitime(Calendar.getInstance().getTime());
		workAttachmentMapper.updateByExampleSelective(entity, example);

		return result;
	}

	@Override
	public ResultDO deleteAll(WorkAttachmentDO domain) {
		ResultDO result = new ResultSupport();

		WorkAttachmentExample example = new WorkAttachmentExample();
		WorkAttachmentExample.Criteria criteria = example.createCriteria();
		if (!isNumberInValid(domain.getWorkPhotographyID())) {
			criteria.andWorkPhotographyIDEqualTo(domain.getWorkPhotographyID());
		}
		List<WorkAttachment> list = workAttachmentMapper.selectByExample(example);
		workAttachmentMapper.deleteByExample(example);

		return result;
	}

	@Override
	public ResultDO setStatus(WorkAttachmentDO domain) {
		ResultDO result = new ResultSupport();
		if (isNumberInValid(domain.getId())) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("参数错误");
			result.setSuccess(false);
			return result;
		}
		if (null == domain.getStatus()
				|| (domain.getStatus() != BonConstant.STATUS_FALSE && domain.getStatus() != BonConstant.STATUS_TRUE)) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("参数错误");
			result.setSuccess(false);
			return result;
		}

		// 修改入底数据状态
		WorkPhotoFilmExample example = new WorkPhotoFilmExample();
		WorkPhotoFilmExample.Criteria criteria = example.createCriteria();
		criteria.andAttachmentIDEqualTo(domain.getId());
		criteria.andBusinessNoEqualTo(domain.getBusinessNo());

		WorkPhotoFilm entity = new WorkPhotoFilm();
		entity.setStatus(domain.getStatus()); // 修改状态
		entity.setComment(domain.getDescription()); // 备注

		workPhotoFilmMapper.updateByExampleSelective(entity, example);

		// 取消选中时，删除入册数据
		if (domain.getStatus() == BonConstant.STATUS_FALSE) {
			workPhotoProductService.deleteByAttachmentID(domain.getId(), domain.getBusinessNo());
		}

		return result;
	}

	@Override
	public ResultDO account(WorkPhotoProductDO domain) {
		ResultDO result = new ResultSupport();
		if (isNumberInValid(domain.getWorkOrderID())) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("参数错误");
			result.setSuccess(false);
			return result;
		}

		WorkAttachmentAccountDO accountDO = new WorkAttachmentAccountDO();
		accountDO.setWorkOrderID(domain.getWorkOrderID());
		accountDO.setBusinessNo(domain.getBusinessNo());
		// TODO: 查询入底基数、入册基数(通过订单id、拍摄场次等查询订单商品信息)
		accountDO.setRdPlan(32); // 入底基数
		accountDO.setRcPlan(32); // 所有商品的入册基数总和

		List<Integer> sources = Arrays.asList(new Integer[] { domain.getSource(), BonConstant.PHOTO_SOURCE_CUSTOMER });

		// 统计照片总数（片源+自备底片）
		WorkPhotoFilmExample example = new WorkPhotoFilmExample();
		WorkPhotoFilmExample.Criteria criteria = example.createCriteria();
		criteria.andWorkOrderIDEqualTo(domain.getWorkOrderID());
		criteria.andBusinessNoEqualTo(domain.getBusinessNo());
		criteria.andSourceIn(sources); // 片源

		accountDO.setTotalNum(workPhotoFilmMapper.countByExample(example));

		// 统计入底数（自备照片不计入入底）
		example.clear();
		criteria = example.createCriteria();
		criteria.andWorkOrderIDEqualTo(domain.getWorkOrderID());
		criteria.andBusinessNoEqualTo(domain.getBusinessNo());
		criteria.andSourceEqualTo(domain.getSource()); // 片源(不包含自备底片)
		criteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL); // 未删除
		criteria.andStatusEqualTo(BonConstant.STATUS_TRUE); // 选中

		accountDO.setRdNum(workPhotoFilmMapper.countByExample(example));

		// 统计入册数
		WorkPhotoProductExample productExample = new WorkPhotoProductExample();
		WorkPhotoProductExample.Criteria productCriteria = productExample.createCriteria();
		productCriteria.andWorkOrderIDEqualTo(domain.getWorkOrderID());
		productCriteria.andBusinessNoEqualTo(domain.getBusinessNo());
		productCriteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL);

		accountDO.setRcNum(workPhotoProductMapper.countAttachmentNum(productExample));

		// 统计未选
		example.clear();
		criteria = example.createCriteria();
		criteria.andWorkOrderIDEqualTo(domain.getWorkOrderID());
		criteria.andBusinessNoEqualTo(domain.getBusinessNo());
		criteria.andSourceIn(sources); // 片源,包含自备底片
		criteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL); // 未删除
		criteria.andStatusEqualTo(BonConstant.STATUS_FALSE); // 未选

		accountDO.setWxNum(workPhotoFilmMapper.countByExample(example));

		// 统计删除
		example.clear();
		criteria = example.createCriteria();
		criteria.andWorkOrderIDEqualTo(domain.getWorkOrderID());
		criteria.andBusinessNoEqualTo(domain.getBusinessNo());
		criteria.andSourceIn(sources); // 片源,包含自备底片
		criteria.andIsDeleteEqualTo(BonConstant.DB_DELETE); // 已删除

		accountDO.setScNum(workPhotoFilmMapper.countByExample(example));

		result.setModel(ResultDO.FIRST_MODEL_KEY, accountDO);
		return result;
	}

}
